//Saturday, December 05 2009
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

class WordsGame
{
public:
	int minimumSwaps(vector <string> grid, string word)
	{
		int ret = 1<<30;
		N = word.length();
		string w = word;
		sort(w.begin(), w.end());
		for(int i=0; i<N; i++)
		{
			string ss = grid[i];
			string s = ss;
			sort(s.begin(), s.end());
			if(s == w) ret = min(ret, cost(ss, word));

			ss.clear();
			for(int j=0; j<N; j++) ss += grid[j][i];
			s = ss;
			sort(s.begin(), s.end());
			if(s == w) ret = min(ret, cost(ss, word));
		}
		return ret == 1<<30 ? -1 : ret;
	}
	int cost(string A, string ref)
	{
		int ret = 0;
		for(int i=0; i<N; i++)
		{
			if(A[i] != ref[i])
			{
				for(int j=0; j<N; j++)
				{
					if(A[i] == ref[j])
					{
						swap(ref[j], ref[i]);
						ret++;
					}
				}
			}
		}
		return ret;
	}
	int N;
};
